import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '../store'

// 引入注册/登录模块
// import Login from '../views/Login/Login.vue'
// import Reg from '../views/Reg/Reg.vue'

// 引入主体模块
// import Main from '../views/Main/Main.vue'

// 引入首页echarts模块页面
// import Home from '../views/Menus/Home/Home.vue'
// import User from '../views/Menus/User/UserInfo.vue'
// import UserAvatar from '../views/Menus/User/UserAvatar.vue'
// import UserPwd from '@/views/Menus/User/UserPwd.vue'
// 引入文章分类页面
// import ArtCate from '@/views/Menus/Article/ArtCate.vue'
// import ArtList from '@/views/Menus/Article/ArtList.vue'

const Login = () => import('../views/Login/Login.vue')
const Reg = () => import('../views/Reg/Reg.vue')
const Main = () => import('../views/Main/Main.vue')
const Home = () => import('../views/Menus/Home/Home.vue')
const User = () => import('../views/Menus/User/UserInfo.vue')
const UserAvatar = () => import('../views/Menus/User/UserAvatar.vue')
const UserPwd = () => import('@/views/Menus/User/UserPwd.vue')
const ArtCate = () => import('@/views/Menus/Article/ArtCate.vue')
const ArtList = () => import('@/views/Menus/Article/ArtList.vue')

// 必须放在创建 VueRouter 对象前
// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err)
}

Vue.use(VueRouter)

// 配置路由规则
const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/', // 网页打开url默认hash值是/路径
    component: Main, // 主体模块
    // 开启路由重定向
    redirect: '/home', // redirect是设置要重定向到哪个路由路径
    // 二级路由是数组 路径不要加/
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'user-info',
        component: User
      },
      {
        path: 'user-avatar',
        component: UserAvatar
      },
      // 重置密码的子路由规则
      {
        path: 'user-pwd',
        component: UserPwd
      },
      {
        path: 'art-cate',
        component: ArtCate
      },
      {
        path: 'art-list',
        component: ArtList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 参数1: 到哪里去
// 参数2: 从哪里来
// 参数3: 是否放行的函数
// 如果没登录(没 token), 则不允许跳转至 /
// 隐含条件: 允许跳转到 /login /reg
// 完整条件: 如果没有登录允许跳转到 /login /reg, 不允许跳到 /
router.beforeEach((to, from, next) => {
  // console.log(store.state.user.token)
  // to.path => /login /reg
  // 可以, 但不够高级
  // if (!store.state.user.token && to.path !== '/login' && to.path !== '/reg') {

  // 扩展性更强, 将来如果添加白名单, 只需要修改数组的元素即可
  const whiteList = ['/login', '/reg']
  // includes: 判断指定的元素是否在数组中, 只能判断基本数据类型, 类似于 indexOf
  if (!store.state.user.token && !whiteList.includes(to.path)) {
    // 调用原型上的方法
    Vue.prototype.$message.error('没有登录啊傻子!')
    next('/login')
  } else {
    next()
  }
})

export default router
